'use client';

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useRouter, useParams } from 'next/navigation';
import styles from './page.module.css';
import { toast } from 'react-hot-toast';

const CommentDetail = () => {
    const router = useRouter();
    const params = useParams();
    const commentId = params?.id;

    const [comment, setComment] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    // 邮件回复相关状态
    const [emailContent, setEmailContent] = useState('');
    const [sending, setSending] = useState(false);

    // 初始化检查
    useEffect(() => {
        if (!commentId) {
            toast.error("评论 ID 不存在");
            router.push('/dashboard/comment-admin');
        }
    }, [commentId, router]);

    // 获取评论详情
    useEffect(() => {
        const fetchComment = async () => {
            try {
                const response = await axios.get(`/api/comment/${commentId}`);
                if (response.data.success) {
                    setComment(response.data.data);
                    // 初始化回复内容（可选）
                    setEmailContent(`您好，关于您的评论："${response.data.data.content.substring(0, 20)}..."，我们的回复是：`);
                } else {
                    throw new Error(response.data.message);
                }
            } catch (err) {
                setError(err.message || '获取评论详情失败');
                toast.error(err.message || '获取评论详情失败');
            } finally {
                setLoading(false);
            }
        };

        if (commentId) fetchComment();
    }, [commentId]);

    // 处理删除
    const handleDelete = async () => {
        if (window.confirm('确定要删除这条评论吗？此操作不可恢复')) {
            try {
                const response = await axios.delete(`/api/comment/${commentId}`);
                if (response.data.success) {
                    toast.success('评论已成功删除');
                    router.push('/dashboard/comment-admin');
                } else {
                    throw new Error(response.data.message);
                }
            } catch (err) {
                toast.error(err.message || '删除失败');
            }
        }
    };

    // 处理状态修改
    const handleStatusChange = async (newStatus) => {
        try {
            const response = await axios.patch(`/api/comment/${commentId}/status`, { status: newStatus });
            if (response.data.success) {
                setComment(prev => ({ ...prev, status: newStatus }));
                toast.success('状态已更新');
            } else {
                throw new Error(response.data.message);
            }
        } catch (err) {
            toast.error(err.message || '更新状态失败');
        }
    };

    // 处理发送回复邮件
    const handleSendEmail = async () => {
        if (!emailContent.trim()) {
            toast.error('请输入回复内容');
            return;
        }

        if (!comment?.email) {
            toast.error('评论者邮箱不存在，无法发送');
            return;
        }

        try {
            setSending(true);
            const response = await axios.post('/api/comment/send-email', {
                to: comment.email,
                subject: `关于您在网站的评论回复`,
                content: emailContent
            });

            if (response.data.success) {
                toast.success('回复邮件已发送');
                setEmailContent(''); // 清空输入框
            } else {
                throw new Error(response.data.message || '发送失败');
            }
        } catch (err) {
            toast.error(err.message || '发送邮件失败，请重试');
        } finally {
            setSending(false);
        }
    };

    if (loading) {
        return (
            <div className={styles.loadingState}>
                <div className={styles.loadingSpinner}></div>
                <p className={styles.loadingText}>加载评论详情中...</p>
            </div>
        );
    }

    if (error || !comment) {
        return (
            <div className={styles.errorState}>
                <div className={styles.errorBox}>
                    <strong>错误:</strong> {error || '评论不存在'}
                </div>
                <button
                    onClick={() => router.push('/dashboard/comment-admin')}
                    className={styles.retryBtn}
                >
                    返回列表
                </button>
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <div className={styles.titleSection}>
                <h1 className={styles.title}>评论详情</h1>
                <button
                    onClick={() => router.back()}
                    className={styles.retryBtn}
                >
                    ← 返回列表
                </button>
            </div>

            <div className={styles.commentListContainer}>
                {/* 评论详情卡片 */}
                <div className={styles.detailCard}>
                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>ID:</span>
                        <span>{comment._id}</span>
                    </div>

                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>用户姓名:</span>
                        <span>{comment.name}</span>
                    </div>

                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>用户邮箱:</span>
                        <span>{comment.email}</span>
                    </div>

                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>评论时间:</span>
                        <span>{new Date(comment.createdAt).toLocaleString()}</span>
                    </div>

                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>当前状态:</span>
                        <span
                            className={`${styles.statusBadge} ${comment.status === 'pending' ? styles.statusPending :
                                comment.status === 'approved' ? styles.statusApproved :
                                    styles.statusRejected
                            }`}
                        >
                            {comment.status === 'pending' ? '待审核' :
                                comment.status === 'approved' ? '已通过' : '已拒绝'}
                        </span>
                    </div>

                    <div className={styles.detailItem}>
                        <span className={styles.detailLabel}>评论内容:</span>
                        <div className={styles.commentContentFull}>{comment.content}</div>
                    </div>

                    <div className={styles.actionBar}>
                        <div className={styles.statusActions}>
                            <span>修改状态:</span>
                            <button
                                onClick={() => handleStatusChange('pending')}
                                disabled={comment.status === 'pending'}
                                className={styles.actionBtn}
                            >
                                待审核
                            </button>
                            <button
                                onClick={() => handleStatusChange('approved')}
                                disabled={comment.status === 'approved'}
                                className={styles.actionBtn + ' ' + styles.approveBtn}
                            >
                                批准
                            </button>
                            <button
                                onClick={() => handleStatusChange('rejected')}
                                disabled={comment.status === 'rejected'}
                                className={styles.actionBtn + ' ' + styles.rejectBtn}
                            >
                                拒绝
                            </button>
                        </div>

                        <button
                            onClick={handleDelete}
                            className={styles.actionBtn + ' ' + styles.deleteBtn}
                        >
                            永久删除
                        </button>
                    </div>
                </div>

                {/* 回复邮件区域 */}
                <div className={styles.emailReplySection}>
                    <h3 className={styles.emailTitle}>发送回复邮件</h3>
                    <div className={styles.emailForm}>
                        <div className={styles.detailItem}>
                            <span className={styles.detailLabel}>收件人:</span>
                            <span>{comment.email}</span>
                        </div>
                        <div className={styles.emailContentContainer}>
                            <label className={styles.detailLabel}>回复内容:</label>
                            <textarea
                                value={emailContent}
                                onChange={(e) => setEmailContent(e.target.value)}
                                placeholder="请输入回复内容..."
                                className={styles.emailTextarea}
                                rows={5}
                            />
                        </div>
                        <button
                            onClick={handleSendEmail}
                            disabled={sending}
                            className={styles.sendEmailBtn}
                        >
                            {sending ? '发送中...' : '发送回复邮件'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default CommentDetail;